<?php 
namespace app\home\controller;

use app\common\controller\HomeBase;
use constant\PayStatus;

/**
 *		微信支付控制器
 */

class Wxpay extends HomeBase {
    private $vendorPath = '';

	// 初始化参数
	public function _initialize() {
		// SDK路径
		$this->vendorPath = ROOT_PATH  . 'public/SDK/Wxpay/';

		require_once $this->vendorPath.'lib/WxPay.Api.php';
		require_once $this->vendorPath.'lib/WxPay.Exception.php';
		require_once $this->vendorPath.'lib/WxPay.Config.php';
		require_once $this->vendorPath.'lib/WxPay.Data.php';
		require_once $this->vendorPath.'lib/WxPay.Notify.php';
		require_once $this->vendorPath.'example/WxPay.NativePay.php';
		require_once $this->vendorPath.'example/log.php';

		$SystemConfigModel = Db('SystemConfig');

		$_api_info = $SystemConfigModel->where('name','wechat_api_parameter')->field('value')->find();
		$api_info = json_decode($_api_info['value'], true);

		$_pay_info = $SystemConfigModel->where('name','wechat_pay_parameter')->field('value')->find();
		$pay_info = json_decode($_pay_info['value'], true);

		// halt($pay_info);

		\WxPayConfig::setAppId($api_info['wechat_appid']);
		\WxPayConfig::setAppSecret($api_info['wechat_appsecret']);

		\WxPayConfig::setMchId($pay_info['wechat_mch_id']);
		\WxPayConfig::setKey($pay_info['wechat_partnerkey']);
	}


	// /**
	//  *  @desc 支付二维码
	//  */
	public function getQrcode($data){

    	$order_sn = $data['order_sn'];

    	$notify = new \NativePay();

    	$input = new \WxPayUnifiedOrder();
    	$input->SetBody('商品购买支付');
    	$input->SetOut_trade_no($order_sn);
    	$input->SetTotal_fee($data['payment_fee'] * 100);
    	$input->SetTime_start(date("YmdHis"));
    	$input->SetTime_expire(date("YmdHis", time() + 600));
    	$notify_url = url('/home/Wxpay/notify', '', true, true);
    	if (isSsl()) {
    		$notify_url = str_replace('http://', 'https://', $notify_url);
    	}
    	$input->SetNotify_url($notify_url);
    	$input->SetTrade_type("NATIVE");
    	$input->SetProduct_id($order_sn);
    	$result = $notify->GetPayUrl($input);

    	$url = $result["code_url"];
    	$url = (isSsl() ? 'https' : 'http') . '://'.$_SERVER['HTTP_HOST'].'/SDK/Wxpay/example/qrcode.php?data='.$url;
    	return $url;
    }


    //异步通知
    public function notify() {
		$WxPayNotify = new \WxPayNotify();

		//初始化日志
		$logPath = ROOT_PATH . '/public/uploads/pay/wx_'.date('Y-m-d').'.log';
		$logHandler= new \CLogFileHandler($logPath);
		$log = \Log::Init($logHandler, 15);

		\Log::DEBUG("begin notify");

		//获取通知的数据
		$xml = $GLOBALS['HTTP_RAW_POST_DATA'];
		file_put_contents('wx_notify.txt',$xml);

		// 如果返回成功则验证签名
		try {
			$data = \WxPayResults::Init($xml);
		} catch (\WxPayException $e){
			$msg = $e->errorMessage();
			\Log::DEBUG($msg);

			$WxPayNotify->SetReturn_code("FAIL");
			$WxPayNotify->SetReturn_msg($msg);
			$WxPayNotify->ReplyNotify(false);
			return;
		}

		$data = \WxPayResults::Init($xml);

		if(!array_key_exists("transaction_id", $data)){
			$msg = "输入参数不正确";
			$WxPayNotify->SetReturn_code("FAIL");
			$WxPayNotify->SetReturn_msg($msg);
			$WxPayNotify->ReplyNotify(false);
			return;
		}
		// 查询订单，判断订单真实性
		if(!$this->Queryorder($data["transaction_id"])){
			$msg = "订单查询失败";
			$WxPayNotify->SetReturn_code("FAIL");
			$WxPayNotify->SetReturn_msg($msg);
			$WxPayNotify->ReplyNotify(false);
			return;
		}

		$out_trade_no = $data['out_trade_no'];
		// 判断缴费记录是否已更新
		$res = model('Order')
		->where('order_sn',$out_trade_no)
		->where('pay_status',PayStatus::HAS_TO_PAID)->count();

		if ($res) {
			//该分支在成功回调到NotifyCallBack方法，处理完成之后流程
			$WxPayNotify->SetReturn_code("SUCCESS");
			$WxPayNotify->SetReturn_msg("OK");
			$WxPayNotify->ReplyNotify(false);
			return;
		}

		$upData = array(
			'pay_status'		=> PayStatus::HAS_TO_PAID,
			'pay_time'			=> strtotime($data['time_end']),
			'pay_code'		    => $data['transaction_id']
		);

		// 修改订单状态
		model('Order')->where('order_sn',$out_trade_no)->update($upData);

		\Log::DEBUG('wxpay success');

		//该分支在成功回调到NotifyCallBack方法，处理完成之后流程
		$WxPayNotify->SetReturn_code("SUCCESS");
		$WxPayNotify->SetReturn_msg("OK");
		$WxPayNotify->ReplyNotify(false);
    }






    private function Queryorder($transaction_id) {
		
    	$input = new \WxPayOrderQuery();
    	$input->SetTransaction_id($transaction_id);
    	$result = \WxPayApi::orderQuery($input);
    	\Log::DEBUG("query:" . json_encode($result));
    	if(array_key_exists("return_code", $result)
    			&& array_key_exists("result_code", $result)
    			&& $result["return_code"] == "SUCCESS"
    			&& $result["result_code"] == "SUCCESS")
    	{
    		return true;
    	}
    	return false;
    }
	
	// /**
	//  * @desc 终端支付之后，腾讯的异步通知
	//  */
	// public function devicePayNotify() {
	// 	$get  = json_encode($_GET);
	// 	$post = json_encode($_POST);
		
	// 	$log_path = './Uploads/tmp/';
	// 	if (!file_exists($log_path)) {
	// 		mkdir($log_path, 0755, true);
	// 	}
	// 	$log_file = $log_path.'wxpay_notify.log';
		
	// 	$log = "[".date('Y-m-d H:i:s')."]\r\nGET: {$get}\r\nPOST: {$post}\r\n\r\n";
	// 	file_put_contents($log_file, $log, FILE_APPEND);
		
	// 	return true;
	// }
	
	// /**
	//  * 获取订单的二维码地址
	//  * @param array $orderData	订单数据
	//  * @return string $url
	//  */
	// public function getOrderQrCode($orderData){
	// 	$out_trade_no = $orderData['out_trade_no'];
		
 //    	$notify = new \NativePay();
    	
 //    	$input = new \WxPayUnifiedOrder();
 //    	$input->SetBody('生意火平台支付');
 //    	$input->SetOut_trade_no($out_trade_no);
 //    	$input->SetTotal_fee($orderData['amount'] * 100);
 //    	$input->SetTime_start(date("YmdHis"));
 //    	$input->SetTime_expire(date("YmdHis", time() + 600));
 //    	$notify_url = U('/Main/Wxpay/notify', '', true, true);
 //    	if (isSsl()) {
 //    		$notify_url = str_replace('http://', 'https://', $notify_url);
 //    	}
 //    	$input->SetNotify_url($notify_url);
 //    	$input->SetTrade_type("NATIVE");
 //    	$input->SetProduct_id($out_trade_no);
 //    	$result = $notify->GetPayUrl($input);
 //    	$url = $result["code_url"];
 //    	$url = (isSsl() ? 'https' : 'http') . '://'.$_SERVER['HTTP_HOST'].'/Application/Common/Library/Vendor/Wxpay/example/qrcode.php?data='.$url;
 //    	return $url;
	// }
}